package com.kcyu.sfherp.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.kcyu.sfherp.config.TimestampConverter;
import com.kcyu.sfherp.entity.utilEntity.SeriesSaleStatistic;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Service
public class ExcelService {

    public void commonExportExcel(HttpServletResponse response, List<?> data, Class clazz, String fileName) throws IOException {
        // 设置response头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileNameEncode = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileNameEncode + ".xlsx");

        WriteCellStyle headStyle = rewriteCellStyle();

        EasyExcel
                .write(response.getOutputStream(), clazz)
                .registerWriteHandler(new HorizontalCellStyleStrategy(headStyle, headStyle))
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerConverter(new TimestampConverter())
                .sheet("sheet1")
                .doWrite(data);

    }

    public WriteCellStyle rewriteCellStyle() {
        WriteCellStyle headStyle = new WriteCellStyle();
        headStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        WriteFont headFont = new WriteFont();
        headFont.setFontHeightInPoints((short) 10);
        headFont.setFontName("宋体");
        headStyle.setWriteFont(headFont);
        headStyle.setBorderTop(BorderStyle.THIN);
        headStyle.setBorderBottom(BorderStyle.THIN);
        headStyle.setBorderLeft(BorderStyle.THIN);
        headStyle.setBorderRight(BorderStyle.THIN);
        return headStyle;
    }

}
